package cn.sirun.com.fca.account.widget;

import android.content.Context;
import android.graphics.Point;
import android.hardware.Camera;
import android.util.DisplayMetrics;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;

import com.tencent.mars.xlog.Log;

import java.io.IOException;
import java.util.List;

import cn.sirun.com.fca.account.uitl.CameraUtils;

/**
 * @author vinsonhuang
 * @date 2018/6/11
 */
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {

    private static String TAG = CameraPreview.class.getName();

    private static final int MIN_HEIGHT = 1080;

    private static final int CAMERA_ID = 0;

    private Context mContext;

    private SurfaceHolder mHolder;

    private Camera mCamera;

    public CameraPreview(Context context) {
        super(context);
        this.mContext = context;
        this.mCamera = getCameraInstance();
        this.mHolder = getHolder();
        this.mHolder.addCallback(this);
        this.mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    /**
     * A safe way to get an instance of the Camera object.
     */
    private static Camera getCameraInstance() {
        Camera c = null;
        try {
            // attempt to get a Camera instance
            c = Camera.open();
        } catch (Exception e) {
            // Camera is not available (in use or does not exist)
            Log.e(TAG, "Camera is not available (in use or does not exist)", e);
        }
        // returns null if camera is unavailable
        return c;
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        startPreview();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        if (null == mHolder.getSurface()) {
            // preview surface does not exist
            return;
        }

        if (null == mCamera) {
            mCamera = getCameraInstance();
        }

        // stop preview before making changes
        try {
            mCamera.stopPreview();
        } catch (Exception e) {
            // ignore: tried to stop a non-existent preview
        }

        // start preview with new settings
        startPreview();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        release();
    }


    /**
     * 对焦，在CameraFragment中触摸对焦
     */
    public void focus() {
        if (null != mCamera) {
            mCamera.autoFocus(null);
        }
    }

    /**
     * 开始预览
     */
    public void startPreview() {
        if (null == mCamera) {
            mCamera = getCameraInstance();
        }

        // 再次判断camera实例是否为空
        if (null == mCamera) {
            Log.e(TAG, "Camera is not available (in use or does not exist)");
            return;
        }

        initCamera();
        CameraUtils.setCameraDisplayOrientation(mContext, CAMERA_ID, mCamera);

        post(new Runnable() {
            @Override
            public void run() {
                try {
                    mCamera.setPreviewDisplay(mHolder);
                    mCamera.startPreview();
                } catch (IOException e) {
                    Log.e(TAG, "Error starting camera preview!", e);
                }
            }
        });

    }

    /**
     * 拍摄照片
     *
     * @param pictureCallback 在pictureCallback处理拍照回调
     */
    public void takePhoto(Camera.PictureCallback pictureCallback) {
        if (null != mCamera) {
            mCamera.takePicture(null, null, pictureCallback);
        }
    }

    public Point getPictureSize() {
        if (null == mCamera) {
            return null;
        }

        Camera.Size size = mCamera.getParameters().getPictureSize();
        return new Point(size.width, size.height);
    }

    /**
     * 释放资源
     */
    public void release() {
        if (null != mCamera) {
            mCamera.setPreviewCallback(null);
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
    }

    private void initCamera() {
        WindowManager manager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);

        Camera.Parameters parameters = mCamera.getParameters();
        List<String> focusModes = parameters.getSupportedFocusModes();
        if (null != focusModes &&
                focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
        } else {
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
        }

        Camera.Size previewSize = CameraUtils.getPropSizeForHeight(parameters
                .getSupportedPreviewSizes(), MIN_HEIGHT);
        parameters.setPreviewSize(previewSize.width, previewSize.height);
        Camera.Size pictureSize = CameraUtils.getPropSizeForHeight(parameters
                .getSupportedPictureSizes(), MIN_HEIGHT);
        parameters.setPictureSize(pictureSize.width, pictureSize.height);
        // 设置照片质量
        parameters.setJpegQuality(100);

        // 竖屏
        mCamera.setDisplayOrientation(90);
        mCamera.setParameters(parameters);
    }

}
